package com.briup.smartlab.web.interceptor;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.briup.smartlab.exception.ServiceException;
import com.briup.smartlab.util.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 拦截用户的业务请求 验证是否登录
 *   当一个接口需要用户进行登录后才能访问 需要先通过拦截器对请求头中的token字符串验证
 *
 * @Author briup
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if(method.equals("OPTIONS")){
            return true;
        }
        String token = request.getHeader("token");
        if(token == null){
            throw new ServiceException("用户未登录，请登录后访问");
        }
        try{
            JWTUtil.checkSign(token);
        }catch (Exception ex){
            if(ex instanceof TokenExpiredException){
                throw new ServiceException("登录超过5分钟，需要重新登录");
            }
            throw new ServiceException("token不合法，重新登录");
        }
        return true;
    }
}
